package cn.wolfcode.p2p.controller;

import cn.wolfcode.p2p.base.anno.NotNeedLogin;
import cn.wolfcode.p2p.base.domain.IpLog;
import cn.wolfcode.p2p.base.domain.LoginInfo;
import cn.wolfcode.p2p.base.exception.CustomException;
import cn.wolfcode.p2p.base.service.ILoginInfoService;
import cn.wolfcode.p2p.base.service.IpLogService;
import cn.wolfcode.p2p.util.JsonResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * 后台登录
 * 登录失败或成功返回信息,返回类型JsonResult
 */
@Controller
public class LoginController {

    @Autowired
    private ILoginInfoService loginInfoService;
    @Autowired
    private IpLogService logService;

    @RequestMapping("/login")
    @ResponseBody
    @NotNeedLogin
    public JsonResult login(LoginInfo loginInfo) {
        int state = IpLog.STATUS_FAILURE; //初始状态为0
        JsonResult jsonResult = JsonResult.instance();
        try {
            loginInfoService.login(loginInfo, LoginInfo.USERTYPE_MGRSITE);
            state = IpLog.STATUS_SUCCESS;
        } catch (CustomException e) {
            jsonResult.setMsg(e.getMessage());

        } catch (Exception e) {
            e.printStackTrace();
            jsonResult.setMsg("系统异常,我们正在殴打程序员");
        }
        //保存登录日志
        logService.save(loginInfo.getUsername(), state,LoginInfo.USERTYPE_MGRSITE);
        return jsonResult;
    }

}
